package com.gui;

import com.gui.exceptions.FailedToGetQuery;
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.util.concurrent.LinkedBlockingQueue;

import org.apache.log4j.Logger;
import com.domain.KBTAQuery;



public class QueryListener extends Thread{
	private LinkedBlockingQueue<KBTAQuery> m_queryList;
	private BufferedReader m_stdIn = null;
	private boolean m_shouldRun;
	protected static Logger s_logger;

        public QueryListener(){
            
        }

	public QueryListener(LinkedBlockingQueue<KBTAQuery> queryQueue) {
		super("QueryListener");
		m_queryList = queryQueue;
		m_shouldRun = true;
		s_logger = Logger.getLogger(QueryListener.class);
		//PropertyConfigurator.configure("D:/workspace/DKBTA/files/conf/log4j.properties");						
	}

	public void run(){
		while(m_shouldRun){
			try{
				KBTAQuery query = getNextQuery();
				if(m_shouldRun)
					m_queryList.put(query);
			}
			catch(FailedToGetQuery ex){				
				s_logger.fatal("Failed to get query. try next");				
			} 
			catch (InterruptedException e) {
				s_logger.fatal("Interrupted while putting query. try next");
			}			
		}
		stopListener();
	}

	private void stopListener() {
		s_logger.info("Stopped! ");
		try {
			m_stdIn.close();
		} catch (IOException e) {
			s_logger.fatal("Failed to close resources");
		}
	}

	protected KBTAQuery getNextQuery() throws FailedToGetQuery{
		KBTAQuery query = new KBTAQuery();
		s_logger.info("Getting next query");
		boolean readQuery = true;
		try{
			while(readQuery){
				String paramName, paramValue;
				System.out.println("***Enter parameter name or type 'done'");
				if(m_stdIn == null)
					m_stdIn = new BufferedReader(new InputStreamReader(System.in));
				paramName = m_stdIn.readLine();
				if(paramName == null || paramName.isEmpty() || paramName.equals("done")){
					readQuery = false;
					break;
				}
				if(paramName.equals("stopq")){
					readQuery = false;
					m_shouldRun = false;
					break;
				}
				System.out.println("***Enter value for <" + paramName + ">");
				paramValue = m_stdIn.readLine();
				s_logger.info("Added pair <" + paramName + "," + paramValue + ">");
				query.addParameterAndValue(paramName, paramValue);
			}
			if(m_shouldRun)
				s_logger.info("Get query ok");
			return query;
		}
		catch (IOException ioe) {
			s_logger.fatal("IO error trying to read input");
			throw new FailedToGetQuery();
		}
		catch(Exception e){
			s_logger.fatal("Unexpected error while trying to read input");
			throw new FailedToGetQuery();
		}
	}

}
